package com.syqc.monitor.ui.historyline

import android.os.Handler
import android.os.Looper
import android.os.Message
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.entity.HistoryLine
import com.syqc.utils.ToolsUtil
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.PublishSubject
import kotlin.math.abs
import kotlin.math.atan

/** @Author Jasper @Time 2020/8/13 @Desc 历史轨迹——轨迹 */
class MapLineViewModel : AutoDisposeViewModel() {
    private var mLocations: List<HistoryLine.Location>? = null
    private var firstMile: Float = 0.0f

    fun setLocations(locations: List<HistoryLine.Location>?) {
        if (locations==null)return
        mLocations = locations
        maxSize = locations.size
        firstMile = locations.first().mile.toFloat()
        for (item in  locations) {
            item.dmile = ToolsUtil.formitNumberD("2", item.mile.toFloat() - firstMile).toString()
        }
    }

    //状态
    private var mPlayState = false
        set(value) {
            playPauseSub.onNext(value)
            field = value
        }

    //速度间隔时间
    var mSpeedTime = 1000

    //定位点位置
    private var progress = 0

    //没改变的时间
    var mNotChangeTime = 1000

    //点集合最大值
    var maxSize = 0

    //线条颜色
    var lineColor: String
        get() = CacheMMKV.decodeString("line_color", "#6C736B")
        set(value) {
            CacheMMKV.encode("line_color", value)
        }

    //当前
    var moveEntity: HistoryLine.Location? = null
    var countEntity: HistoryLine.CountData? = null

    private val totalList by lazy { ArrayList<LatLng>() }
    private val totalListSub by lazy { PublishSubject.create<ArrayList<LatLng>>() }
    fun totalListObserver(): Observable<java.util.ArrayList<LatLng>> = totalListSub.hide()

    private val playPauseSub by lazy { PublishSubject.create<Boolean>() }
    fun playPauseObserver(): Observable<Boolean> = playPauseSub.hide()
    private val maxSub by lazy { PublishSubject.create<Boolean>() }
    fun maxObserver(): Observable<Boolean> = maxSub.hide()

    var isShowTotal = true

    val progressSub by lazy { PublishSubject.create<Int>() }

    //全部定位点
    val mAllPoints by lazy { ArrayList<LatLng>() }

    //移动
    val mMoveEntitySub: PublishSubject<HistoryLine.Location>
            by lazy { PublishSubject.create<HistoryLine.Location>() }

    /** 设置轨迹线 */
    fun setPolyLine(): LatLngBounds? {
        mLocations?.run {
            mAllPoints.clear()
            val bounds = LatLngBounds.builder()
            for (location in this) {
                val latLng = LatLng(location.lat.toDouble(), location.lng.toDouble())
                mAllPoints.add(latLng)
                bounds.include(latLng)
            }
            return bounds.build()
        }

        return null
    }


    private val mHandle: Handler by lazy{
        object : Handler(Looper.getMainLooper()) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                if (msg.what == 1) {
                    setProgress()
                    progress++
                    sendEmptyMessageDelayed(1, mSpeedTime.toLong())
                } else if (msg.what == 2) {
                    removeMessages(1)
                }
            }
        }
    }

    /** 设置进度 */
    private fun setProgress() {

        if (progress > maxSize - 1) {
            pausePlay()
            return
        }
        progressSub.onNext(progress)
        mMoveEntitySub.onNext( mLocations!![progress])
    }

    /** 轨迹播放暂停 */
    fun onPlayPause() {
        isStop = false
        if (mPlayState) {
            mPlayState = false
            mHandle.sendEmptyMessage(2)
        } else {
            if (progress >= maxSize - 1) {
                progress = 0
                progressSub.onNext(progress)
                maxSub.onNext(true)
            }
            mPlayState = true
            mHandle.sendEmptyMessage(1)

        }
    }

    /** 暂停播放 */
    fun pausePlay() {
        mPlayState = false
        mHandle.sendEmptyMessage(2)
    }

    private var isStop: Boolean = false

    /** 停止播放 */
    fun onStopPlay() {
        if (isStop) return
        isStop = true

        progress = 0
        setProgress()

        mPlayState = false
        mHandle.sendEmptyMessage(2)
    }

    /** 拖动位置 */
    fun scrollTo(position: Int) {
        isStop = false
        pausePlay()
        mLocations?.let {
            progress = position
            moveEntity = it[position]
            totalList.clear()
            if (position == 0) {
                totalList.add(LatLng(moveEntity!!.lat.toDouble(), moveEntity!!.lng.toDouble()))
            } else {
                val subList = it.subList(0, position)
                for (entity in subList) {
                    totalList.add(LatLng(entity.lat.toDouble(), entity.lng.toDouble()))
                }
            }
            totalListSub.onNext(totalList)
        }
    }

    /** 播放速度 */
    fun speedChange(change: Int) {
        var long = change
        long -= mNotChangeTime
        if (abs(long) < 20) {
            long = 20
        }
        mSpeedTime = abs(long)

    }

    /** 根据两点算取图标转的角度 */
    fun getRotate(fromPoint: LatLng, toPoint: LatLng): Double {
        val slope = getSlope(fromPoint, toPoint)
        if (slope == Double.MAX_VALUE) {
            return (if (toPoint.latitude > fromPoint.latitude) {
                0
            } else {
                180
            }).toDouble()
        }
        var deltAngle = 0f
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180f
        }
        val radio = atan(slope)
        return 180 * (radio / Math.PI) + deltAngle - 90
    }


    /** 算斜率 */
    private fun getSlope(fromPoint: LatLng, toPoint: LatLng): Double {
        return if (toPoint.longitude == fromPoint.longitude) {
            Double.MAX_VALUE
        } else (toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude)
    }

    override fun onCleared() {
        super.onCleared()
        mHandle.removeMessages(1)

    }
}